package com.wenan.data
{
	import mx.collections.ArrayList;
	import mx.collections.IList;
	import com.wenan.ui.controls.flashMaps.WenAnMapSprite;
	
	public class CityCollection
	{
		private var _map:WenAnMapSprite;
		private var _innerList:ArrayList = new ArrayList();
		
		public function CityCollection(map:WenAnMapSprite)
		{
			this._map = map;
		}
		
		public function get map():WenAnMapSprite
		{
			return _map;
		}
		
		public function getList():IList
		{
			return _innerList;
		}
		
		public function get length():int
		{
			return _innerList.length;
		}
		
		public function getAt(index:int):City
		{
			return _innerList.getItemAt(index) as City;
		}
		
		public function getIndexByName(cityName:String):int
		{
			for(var i:int=0;i<_innerList.length;i++)
			{
				var city:City = _innerList.getItemAt(i) as City;
				if (city.name == cityName)
				{
					return i;
				}
			}
			return -1;
		}
		
		public function findByName(cityName:String):City
		{
			var index:int = getIndexByName(cityName);
			if (index < 0)
			{
				return null;
			}
			return _innerList.getItemAt(index) as City;
		}
		
		public function getByName(cityName:String):City
		{
			var city:City = findByName(cityName);
			if (city == null) 
			{
				throw new Error("无法找到名称为 \""+cityName+"\" 的城市.");
			}
			return city;
		}
		
		public function add(city:City):void
		{
			_innerList.addItem(city);
			addImage(city);
		}
		
		public function insert(index:int, city:City):void
		{
			_innerList.addItemAt(city, index);	
			addImage(city);
		}
		
		public function remove(city:City):void
		{
			_innerList.removeItem(city);
			removeImage(city);
		}
		
		public function removeAt(index:int):void
		{
			var city:City=_innerList.getItemAt(index) as City;
			_innerList.removeItemAt(index);	
			removeImage(city);
		}
		
		public function clear():void
		{
			for each(var city:City in _innerList)
			{
				removeImage(city);
			}
			_innerList.removeAll();
		}
		
		public function toArray():Array
		{
			return _innerList.toArray();
		}
		
		private function addImage(city:City):void
		{
			_map.addChild(city.image);
		}
		
		private function removeImage(city:City):void
		{
			_map.removeChild(city.image);
		}
	}
}